package com.strongbj.iot.devices.dam.request.handle.damtoscreen;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.common.NetMapping;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.dam.request.entity.AssetInfoOfBindRFIDEntity;
import com.strongbj.iot.devices.dam.sub.dacai.entity.DaCaiBindRFIDMenuManager;
import com.strongbj.iot.devices.dam.sub.dacai.entity.DaCaiBindRFIDMenuManager.MenuItem;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 更新绑定RFID的菜单处理
 * @author yuzhantao
 *
 */
public class UpdateBindRFIDMenuHandle implements IMessageHandle<MQMessageOfDAM, Object> {
	private static Logger logger = LogManager.getLogger(UpdateBindRFIDMenuHandle.class.getName());
	private static final String ACTION_CODE = "updateBindRfidMenu";
	private static final byte[] CLEAR_TABLE_MESSAGE = {(byte)0xEE,(byte)0xB1 ,(byte)0x53 ,(byte)0x00 ,(byte)0x0B ,(byte)0x00 ,(byte)0x01 ,(byte)0xFF ,(byte)0xFC ,(byte)0xFF ,(byte)0xFF };
	private static final byte[] DAM_DEVICE_CODE= {(byte)0x00,(byte)0x00,(byte)0x00};
	private static final String ADD_TABLE_COMMAND_HEADER="EEB152000B0001";
	private static final String ADD_TABLE_COMMAND_FOOTER="FFFCFFFF";
	private static final byte[] LOAD_FINISH_MESSAGE = {(byte)0xEE , (byte)0xB1 , (byte)0x10 , (byte)0x00 , (byte)0x0A , (byte)0x03 , (byte)0xE6 , (byte)0xBC , (byte)0xD3 , (byte)0xD4 , (byte)0xD8 , (byte)0xCD , (byte)0xEA , (byte)0xB3 , (byte)0xC9 , (byte)0xFF, (byte)0xFC , (byte)0xFF, (byte)0xFF};
	private static final DAMMessageFactory damMessageFactory = new DAMMessageFactory(); // DAM消息工厂
	
	@Override
	public boolean isHandle(MQMessageOfDAM t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 将收到的屏幕命令下发到屏幕硬件
	 */
	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfDAM t) {
		String deviceCode = ((JSONObject) t.getAwsPostdata()).getString("deviceAddress");
		Channel channel = NetMapping.getInstance().getChannel(deviceCode);
		
		// 清除资产菜单中的显示内容
		ITaskManager taskManager = DAMManager.getTaskManager(deviceCode);
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				try {
				sendClearAssetMenuMessage(channel);
				Thread.sleep(500);
				}catch(Exception e) {
					logger.error(e);
				}
			}
			
		});
		
		List<AssetInfoOfBindRFIDEntity> assetList = ((JSONObject)t.getAwsPostdata()).getJSONArray("assetList").toJavaList(AssetInfoOfBindRFIDEntity.class);
		
		List<MenuItem> menuItemList = new ArrayList<>();
		for(int i=0;i<assetList.size();i++) {
			MenuItem menuItem = DaCaiBindRFIDMenuManager.getInstance().new MenuItem();
			menuItem.setAssetId(String.valueOf(assetList.get(i).getId()));
			menuItem.setAssetName(assetList.get(i).getAssetName());
			menuItem.setStartU(assetList.get(i).getStartU());
			menuItemList.add(menuItem);
			
			final int index = i;
			taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
				@Override
				protected void taskRun() {
					try {
						StringBuffer sb = new StringBuffer();
						AssetInfoOfBindRFIDEntity asset = assetList.get(index);
						sb.append(asset.getStartU()+";");
						sb.append(asset.getAssetNo()+";");
						sb.append(asset.getAssetName()+";");
						sb.append(asset.getAssetModelName()+";");
						sendSetAssetMenuMessage(channel,sb.toString());
						sb.setLength(0);
					}catch(Exception e) {
						logger.error(e);
					}
				}
				
			});
		}
		
		DaCaiBindRFIDMenuManager.getInstance().addMenu(deviceCode, menuItemList); // 将机柜中的资产添加到大彩绑定RFID菜单的界面中
		
		// 发送加在完成提示到文本控件
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				try {
					byte[] datas = createMessage(LOAD_FINISH_MESSAGE);
					sendMessage(channel,datas);
				}catch(Exception e) {
					logger.error(e);
				}
			}
			
		});
		return null;
	}
	
	/**
	 * 发送清除资产菜单命令
	 * @param ctx
	 * @param devAddress
	 * @param isOpen
	 * @throws UnsupportedEncodingException
	 */
	private void sendClearAssetMenuMessage(Channel channel) {
		byte[] datas = createClearAssetMenuMessage();
		ChannelFuture cf = channel.writeAndFlush(Unpooled.copiedBuffer(datas));
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("向屏幕绑定RFID菜单下发清除显示内容命令成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("向屏幕绑定RFID菜单下发清除显示内容命失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	/**
	 * 创建清除资产菜单的命令
	 * @return
	 */
	private byte[] createClearAssetMenuMessage() {
		return damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()), DAM_DEVICE_CODE, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				(byte) 0xFF, // 向屏幕发送命令
				CLEAR_TABLE_MESSAGE // 清除资产菜单
		);
	}
	
	private void sendMessage(Channel channel,byte[] datas) throws UnsupportedEncodingException {
		ChannelFuture cf = channel.writeAndFlush(Unpooled.copiedBuffer(datas));
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("向屏幕绑定RFID菜单下发设置显示内容命令成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("向屏幕绑定RFID菜单下发设置显示内容命失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}
	private void sendSetAssetMenuMessage(Channel channel,String msg) throws UnsupportedEncodingException {
		byte[] datas = createSetAssetMenuMessage(msg);
		sendMessage(channel,datas);
	}
	
	/**
	 * 创建设置资产菜单信息
	 * @param msg
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private byte[] createSetAssetMenuMessage(String msg) throws UnsupportedEncodingException {
		StringBuffer sb = new StringBuffer(ADD_TABLE_COMMAND_HEADER);
		byte[] datas = msg.getBytes("GBK");
		sb.append(ByteUtil.byteArrToHexString(datas));  // 控件内容
		sb.append(ADD_TABLE_COMMAND_FOOTER);
		
		return damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()), DAM_DEVICE_CODE, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				(byte) 0xFF, // 向屏幕发送命令
				ByteUtil.hexStringToBytes(sb.toString()) // 设置资产菜单内容
		);
	}
	
	private byte[] createMessage(byte[] datas) throws UnsupportedEncodingException {
		return damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()), DAM_DEVICE_CODE, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				(byte) 0xFF, // 向屏幕发送命令
				datas // 设置资产菜单内容
		);
	}
}
